import React from 'react';
import { Tooltip, Table, Divider, Button, Modal, Popconfirm, Card, Space, Upload, message } from 'antd';
import {
  FormOutlined,
  PlusOutlined,
  PlusSquareOutlined,
  DeleteOutlined,
  SyncOutlined,
  ExportOutlined,
  ImportOutlined,
} from '@ant-design/icons';
import { connect } from 'umi';
import CateEdit from './cateedit';
import request from '@/utils/request';
import UploadUtil from '@/components/UploadUtil';
import { Scrollbars } from 'react-custom-scrollbars';

class ViewForm extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      dataSource: [],
      cateid: 0,
      parentCate: {},
      ids: [],
    };
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData = () => {
    this.setState({ loading: true });
    this.props
      .dispatch({
        type: 'Abp/getTreeList',
        payload: { layout: this.props.layout },
        control: 'Category',
      })
      .then(() => {
        this.setState({ loading: false, dataSource: this.props.response.result });
      });
  };
  showModal = (val: any) => {
    this.setState({
      visible: val,
    });
  };
  editCate(cid: any) {
    var _this = this;
    this.setState(
      {
        cateid: cid,
        parentCate: {},
      },
      function () {
        _this.showModal(true);
      },
    );
  }
  addSubCate(pid: any) {
    var _this = this;
    this.setState(
      {
        cateid: 0,
        parentCate: pid,
      },
      function () {
        _this.showModal(true);
      },
    );
  }
  addCate(pid: any) {
    var _this = this;
    this.setState(
      {
        cateid: 0,
        parentCate: {},
      },
      function () {
        _this.showModal(true);
      },
    );
  }
  handleDelete(val: any) {
    this.setState({ loading: true });
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { id: val },
        control: 'Category',
      })
      .then(() => {
        this.setState({
          loading: false,
        });
        this.fetchData();
      });
  }
  async handlerExport() {
    const { layout } = this.props;
    var resp = await request('/api/Excel/ExportCate?layout=' + layout, {
      method: 'POST',
      responseType: 'blob',
    })
    var url = window.URL.createObjectURL(resp);
    var a = document.createElement('a');
    a.href = url;
    a.download = 'ExportCate.xls';
    a.click();
  }
  handlerImport = (info: any) => {
    if (info.file.status === "done") {
      message.success("导入成功");
      this.fetchData();
    }
  };
  render() {
    const columns = [
      {
        title: '信息分类',
        dataIndex: 'categoryName',
        key: 'categoryName',
      },
      {
        title: '索引',
        dataIndex: 'categoryIndex',
        key: 'categoryIndex',
      },
      {
        title: '操作',
        key: 'action',
        render: (text: any, record: any) =>
          this.state.dataSource.length >= 1 ? (
            <span>
              <Tooltip placement="left" title="编辑">
                <a onClick={() => this.editCate(record.id)}>
                  <FormOutlined />
                </a>
              </Tooltip>
              <Divider type="vertical" />
              <Tooltip placement="bottom" title="添加子类">
                <a onClick={() => this.addSubCate(record)}>
                  <PlusSquareOutlined />
                </a>
              </Tooltip>
              <Divider type="vertical" />
              <Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(record.id)}>
                <Tooltip placement="bottom" title="删除类别">
                  <a>
                    <DeleteOutlined style={{ color: 'red' }} />
                  </a>
                </Tooltip>
              </Popconfirm>
            </span>
          ) : null,
      },
    ];
    const rowSelection = {
      onChange: (selectedRowKeys: any, selectedRows: any) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
      getCheckboxProps: (record: any) => ({
        name: record.name,
      }),
    };
    return (
      <div>
        <Card
          size={this.props.size}
          extra={
            <Space>
              <Tooltip title="新增">
                <Button type="default" onClick={() => this.addCate(0)} icon={<PlusOutlined />}>
                  新增
                </Button>
              </Tooltip>
              <Tooltip title="刷新">
                <Button type="default" onClick={() => this.fetchData()} icon={<SyncOutlined />}>
                  刷新
                </Button>
              </Tooltip>
              <Tooltip title="导出">
                <Button type="primary" onClick={() => this.handlerExport()} icon={<ExportOutlined />}>
                  导出
                </Button>
              </Tooltip>
              <Upload
                accept=".xls,.xlsx,application/vnd.ms-excel"
                name='file'
                //action={UploadUtil.serverUrl + "/api/Excel/ImportCate"}
                action="/api/Excel/ImportCate"
                headers={{
                  Authorization: UploadUtil.accessToken,
                }}
                beforeUpload={UploadUtil.checkExcel}
                showUploadList={false}
                onChange={this.handlerImport}
              >
                <Button icon={<ImportOutlined />}>导入</Button>
              </Upload>
            </Space>
          }
        >
          <Scrollbars autoHide style={{ height: 300 }}>
            <Table
              rowKey={(record) => record.id}
              showHeader={false}
              columns={columns}
              dataSource={this.state.dataSource}
              loading={this.state.loading}
              pagination={false}
              size={this.props.size}
              rowSelection={rowSelection}
            />
          </Scrollbars>
          <Modal
            title="分类编辑"
            visible={this.state.visible}
            onCancel={() => this.showModal(false)}
            footer={null}
            destroyOnClose
          >
            <CateEdit
              RefreshData={() => this.fetchData()}
              cateid={this.state.cateid}
              parentCate={this.state.parentCate}
              layout={this.props.layout}
            />
          </Modal>
        </Card>
      </div>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewForm);
